// 引入各种资源包
const gulp = require('gulp')
const sass = require('gulp-sass')(require('sass')) // 引入编译 sass 包
const del = require('del') // 引入清理 dist 目录包
const connect = require('gulp-connect')// 引入启动wedsever包
const uglify = require('gulp-uglify')
const babel = require('gulp-babel') // 转译js 包
const cleanCSS = require('gulp-clean-css')
const htmlmin = require('gulp-htmlmin')

// 定义变量，保存各种资源路径
const paths = {
  js: {
    src: 'src/js/**/*.js', // js 文件的源路径
    dest: 'dist/js' // 处理之后保存的路径
  },
  css: {
    src: 'src/css/**/*.css',
    dest: 'dist/css'
  },
  scss: {
    src: 'src/scss/**/*.scss',
    dest: 'dist/css'
  },
  html: {
    src: 'src/**/*.html',
    dest: 'dist'
  },
  libs: {
    src: 'src/libs/**/*.*',
    dest: 'dist/libs'
  },
  imgs: {
    src: 'src/imgs/**/*.*',
    dest: 'dist/imgs'
  },
  json: {
    src: 'src/json/**/*.*',
    dest: 'dist/json'
  }
}

// 压缩、转译 JS 任务
function scripts() {
  return gulp.src(paths.js.src)
    .pipe(babel({
      presets: ['env']
    }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.js.dest))
    .pipe(connect.reload())
}
// 压缩 CSS 任务
function styles() {
  return gulp.src(paths.css.src)
    .pipe(cleanCSS())
    .pipe(gulp.dest(paths.css.dest))
    .pipe(connect.reload())
}
// 压缩 SCSS 任务,编译风格 outputStyle: 'compressed'
function buildScss() {
  return gulp.src(paths.scss.src)
    .pipe(sass({ outputStyle: 'compressed' }))
    .pipe(gulp.dest(paths.scss.dest))
    .pipe(connect.reload())
}
// 处理 html 文件
function html() {
  return gulp.src(paths.html.src)
    .pipe(htmlmin({
      collapseWhitespace: true,
      minifyCSS: true, minifyJS: true
    }))
    .pipe(gulp.dest(paths.html.dest))
    .pipe(connect.reload())
}

// 定义监视任务
function watch() {
  gulp.watch(paths.scss.src, buildScss)
  gulp.watch(paths.js.src, scripts)
  gulp.watch(paths.css.src, styles)
  gulp.watch(paths.html.src, html)
}

// 清理 dist 目录
function clean() {
  return del(['dist'])
}
// 复制无需特殊处理的 库 资源
function copyLibs() {
  return gulp.src(paths.libs.src)
    .pipe(gulp.dest(paths.libs.dest))
}
// 复制 json 数据
function copyJson() {
  return gulp.src(paths.json.src)
    .pipe(gulp.dest(paths.json.dest))
}
// 复制图片的资源
function copyImgs() {
  return gulp.src(paths.imgs.src)
    .pipe(gulp.dest(paths.imgs.dest))
}
// 启动 wedsever 
function sever() {
  connect.server({
    root: 'dist',
    port: 9527,
    livereload: true
  })
}
// 形成处理流程
const build = gulp.series(clean, gulp.parallel(styles, copyJson, scripts, buildScss, html, copyLibs, copyImgs, watch, sever))

// 导出任务
exports.scripts = scripts
exports.styles = styles
exports.buildScss = buildScss
exports.watch = watch
exports.html = html
exports.clean = clean
exports.copyLibs = copyLibs
exports.copyImgs = copyImgs
exports.sever = sever
exports.copyJson = copyJson
exports.build = build

// 默认任务
exports.default = build

